package org.ljp2010.bot.sinaweibo1;

public class MultiPartData {
	// Headers = {parname, parvalue,parname,parvalue,...};
	public String Headers[];
	public byte Data[];

	private int s = 0;

	public byte[] GetData() {
		byte r[] = new byte[GetSize()];
		int p = 0;

		try {
			for (int i = 0; i < Headers.length / 2; i++) {
				byte[] b1 = Headers[i * 2].getBytes("utf-8");
				System.arraycopy(b1, 0, r, p, b1.length);
				p = p + b1.length;

				r[p++] = ':';
				r[p++] = ' ';

				byte[] b2 = Headers[i * 2 + 1].getBytes("utf-8");
				System.arraycopy(b2, 0, r, p, b2.length);
				p = p + b2.length;
				r[p++] = '\r';
				r[p++] = '\n';
			}
		} catch (Exception e) {
			System.out.println("Encode utf-8 failed, "
					+ "can't input multipart data to the buffer.");
		}
		r[p++] = '\r';
		r[p++] = '\n';

		System.arraycopy(Data, 0, r, p, Data.length);
		p = p + Data.length;

		r[p++] = '\r';
		r[p++] = '\n';

		return r;
	}

	public int GetSize() {
		if (s != 0)
			return s;

		try {
			for (int i = 0; i < Headers.length / 2; i++) {
				s = s + Headers[i * 2].getBytes("utf-8").length + 2 // ": "
						+ Headers[i * 2 + 1].getBytes("utf-8").length + 2; // "\r\n"
			}
			s = s + 2; // "\r\n"
			s = s + Data.length + 2; // "\r\n";
		} catch (Exception e) {
			System.out.println("Encode utf-8 failed, "
					+ "can't get multipart data length.");
		}
		return s;
	}
}
